import { useLocation } from "@tanstack/react-router";
import {
	type PropsWithChildren,
	memo,
	useEffect,
	useMemo,
	useRef,
} from "react";

function MemoizedScrollTop({ children }: PropsWithChildren) {
	const domRef = useRef<HTMLDivElement>(null);
	const location = useLocation();

	const scrollHistoryMap = useRef<Map<string, number>>(new Map());
	const activeKey = useMemo(() => location.href, [location.href]);

	useEffect(() => {
		const divDom = domRef.current;
		if (!divDom) return;

		console.log(`${activeKey} activated`);
		if (scrollHistoryMap.current.has(activeKey)) {
			setTimeout(() => {
				divDom.scrollTo(0, scrollHistoryMap.current.get(activeKey) || 0);
			}, 500);
		}

		const onScroll = (e: Event) => {
			const target = e.target as HTMLDivElement;
			if (!target) return;
			scrollHistoryMap.current.set(activeKey, target?.scrollTop || 0);
		};
		divDom?.addEventListener("scroll", onScroll);
		return () => {
			divDom?.removeEventListener("scroll", onScroll);
		};
	}, [activeKey]);

	return (
		<div
			ref={domRef}
			className="h-full w-full overflow-x-hidden overflow-y-auto"
		>
			{children}
		</div>
	);
}

export default memo(MemoizedScrollTop);
